package org.jeecgframework.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.fr.base.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.controller.CbsQuickRepairController;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.service.ZyContactsServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.system.service.impl.SystemServiceImpl;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.sendWxMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 大伟 on 2017/1/8.
 * Description
 */
@Service("wxCommonService")
public class WxCommonServiceImpl extends CommonServiceImpl implements WxCommonService {


    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsQuickRepairController.class);
    @Autowired
    private SystemService systemService;

    @Autowired
    private UserService userService;

    @Autowired
    private ZyContactsServiceI zyContactsService;

    @Override
    public synchronized String generateServiceId(ServiceEnum type) {
        return "S" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
    }

    public void sendServiceMail(ServiceEnum type, String id) {

        Map param = new HashMap();
        switch (type) {
            case YQFX:
                param.put("page", get(CbsYqReconditionEntity.class, id));
                break;
            case GGFX:
                param.put("page", get(CbsGgReconditionEntity.class, id));
                break;
            case SBYJ:
                param.put("page", get(CbsMerchineMoveEntity.class, id));
                break;
            case XJYY:
                param.put("page", get(CbsInsApplicationEntity.class, id));
                break;
            case YBSQ:
                param.put("page", get(CbsExtWarrantyEntity.class, id));
                break;
        }
        CbsServiceBaseEntity base = (CbsServiceBaseEntity) param.get("page");
        param.put("serviceType", type.getMsg());
        List<TSType> mailType = findHql("from TSType where TSTypegroup.typegroupcode=?", StaticValue.DIC_SERVICE_MAILADDRESS);
        List<TSUser> user = findHql("from TSUser where mobilePhone=?", base.getContactsPhone());
        if (user.size() > 0) {
            if (!base.getContactsName().equals(user.get(0).getRealName())) {
                param.put("nameChangeBefore", user.get(0).getRealName());
                param.put("nameChangeAfter", base.getContactsName());
            }
        }

        for (TSType tsType : mailType) {
            if (StringUtil.isNotEmpty(tsType.getTypename())) {
                ZyEmailEntity email = new ZyEmailEntity();
                email.setEmailReceiver(tsType.getTypename());
                email.setEmailSubject(StaticValue.DIC_SERVICE_MAIL_PREFIX + '-' + type.getMsg() + '-' + base.getServiceId() + "-" + base.getCinemaName());
                SendMailUtil.sendFtlMail(email, "mail_wx_service.ftl", param, systemService);
            }
        }
        try {
            //单独给 JV-helpdesk@barco.com 发
            ZyEmailEntity email = new ZyEmailEntity();
            email.setEmailReceiver("dl_bjv_helpdesk@cfg-barco.com");
            email.setEmailSubject(StaticValue.DIC_SERVICE_MAIL_PREFIX + '-' + type.getMsg() + '-' + base.getServiceId() + "-" + base.getCinemaName());
            SendMailUtil.sendFtlMail(email, "mail_wx_service.ftl", param, systemService);
            email = new ZyEmailEntity();
            email.setEmailReceiver("wx@cfg-barco.com");
            email.setEmailSubject(StaticValue.DIC_SERVICE_MAIL_PREFIX + '-' + type.getMsg() + '-' + base.getServiceId() + "-" + base.getCinemaName());
            SendMailUtil.sendFtlMail(email, "mail_wx_service.ftl", param, systemService);
        } catch (Exception e) {
        }
    }

    /*
     * 原微信查询增值产品列表功能
     * */
    public List<? extends CbsServiceBaseEntity> getList(ServiceEnum type, String phone) {
        String hqlEntity = "";
        String serviceType1 = "";
        String serviceType2 = "";
        if (StringUtil.isEmpty(phone) && null != ResourceUtil.getSessionUserName()) {
            phone = ResourceUtil.getSessionUserName().getMobilePhone();
        }
        switch (type) {
            case YQFX:
                hqlEntity = "CbsYqReconditionEntity";
                serviceType1 = "增值服务";
                serviceType2 = "引擎翻新";
                break;
            case GGFX:
                hqlEntity = "CbsGgReconditionEntity";
                serviceType1 = "增值服务";
                serviceType2 = "光管翻新";
                break;
            case SBYJ:
                hqlEntity = "CbsMerchineMoveEntity";
                serviceType1 = "增值服务";
                serviceType2 = "移机";
                break;
            case XJYY:
                hqlEntity = "CbsInsApplicationEntity";
                serviceType1 = "增值服务";
                serviceType2 = "巡检";
                break;
            case YBSQ:
                hqlEntity = "CbsExtWarrantyEntity";
                serviceType1 = "咨询";
                serviceType2 = "维修咨询";
                break;
        }
        return findHql("from " + hqlEntity + " where contactsPhone=? order by createDate desc", oConvertUtils.getString(phone));
    }

    /*
     * 现微信查询增值产品列表功能
     * 开发人：mhg
     * 时间：2018-04
     * */
    public List<? extends CbsServiceBaseEntity> getListNew(ServiceEnum type, String phone) {
        String hqlEntity = "";
        String serviceType1 = "";
        String serviceType2 = "";
        if (StringUtil.isEmpty(phone) && null != ResourceUtil.getSessionUserName()) {
            phone = ResourceUtil.getSessionUserName().getMobilePhone();
        }
        switch (type) {
            case YQFX:
                hqlEntity = "CbsServiceEntity";
                serviceType1 = "增值服务";
                serviceType2 = "引擎翻新";
                break;
            case GGFX:
                hqlEntity = "CbsServiceEntity";
                serviceType1 = "增值服务";
                serviceType2 = "光管翻新";
                break;
            case SBYJ:
                hqlEntity = "CbsServiceEntity";
                serviceType1 = "增值服务";
                serviceType2 = "移机";
                break;
            case XJYY:
                hqlEntity = "CbsServiceEntity";
                serviceType1 = "增值服务";
                serviceType2 = "巡检预约";
                break;
            case YBSQ:
                hqlEntity = "CbsServiceEntity";
                serviceType1 = "咨询";
                serviceType2 = "维保咨询";
                break;
            case XJBG:
                hqlEntity = "CbsServiceEntity";
                serviceType1 = "增值服务";
                serviceType2 = "巡检变更";
                break;
        }

        return findHql("from " + hqlEntity + " where contactsPhone=? and serviceType1.name='" + serviceType1 + "' and serviceType2.name='" + serviceType2 + "' and sourceType='2' order by createDate desc", oConvertUtils.getString(phone));
    }

    public TSUser initUserWithPhoneAndName(String phone, String realName, HttpServletRequest request) {
        TSUser user = new TSUser();
        if (StringUtil.isEmpty(phone) || StringUtils.isEmpty(realName)) {
            return null;
        }
        String openId = (String) request.getSession().getAttribute("openId");
        //微信头像
        String headImg = (String) request.getSession().getAttribute("headImg");
        List<TSUser> users = userService.getUserByMobilePhone(phone);
        if (users.size() > 0) {
            user = users.get(0);
            if (StringUtil.isEmpty(user.getOpenId())) {
                user.setOpenId(openId);
                user.setAuthenticationLevel("1");
                super.saveOrUpdate(user);

                List<ZyContactsEntity> ct = findHql("from ZyContactsEntity where tsBaseUser.id=?", user.getId());
                if (ct.size() == 0) {
                    zyContactsService.addContactByUser(user);
                }
            }
        } else {
            user = userService.addWxUser(openId, realName, null, phone, "1", headImg);
            zyContactsService.addContactByUser(user);
        }
        systemService.addLog("微信用户" + openId + "注册成功。", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
        return user;
    }


    /**
     * 提交完服务单，给HD发送邮件
     */
    public void sendMail(CbsServiceEntity service) {
        System.out.println("发送邮件。。。。");
        String serviceType = "";
        String serviceCode = "";
        String sn = "";
        String cinamaName = "";
        String name = "";
        String phone = "";
        String errDes = "";

        if (service != null) {
            serviceCode = service.getCode();
            sn = service.getSn();
            cinamaName = service.getZyCinemaName();
            name = service.getContactsName();
            phone = service.getContactsPhone();
            errDes = service.getDescription();
            if (service.getServiceType2() != null) {
                serviceType = service.getServiceType2().getName();
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
        String emailTitle = "微信服务通知：" + serviceType + "-" + serviceCode + "-" + sn + "-" + cinamaName + "-" + sdf.format(new Date()) + "";
        Map<String, Object> paraMap1 = new HashMap<>();
        paraMap1.put("name", name);
        paraMap1.put("phone", phone);
        paraMap1.put("errDes", errDes);
     // start 181221 Amy 修改收件人为组邮箱 
        ZyEmailEntity eMail = new ZyEmailEntity();
        eMail.setEmailSubject(emailTitle);
        eMail.setEmailReceiver(StaticValue.COMMON_EMAIL_ADDRESS);
        SendMailUtil.sendFtlMail(eMail, "mail_wx_sub_service.ftl", paraMap1, systemService);
        System.out.println("给HD发送邮件。。。。");
//        //获取所有HD
//        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSRole.roleCode='" + StaticValue.CBS_HD_ROLE_CODE + "'");
//        if (tsRoleUserList != null && tsRoleUserList.size() > 0) {
//            for (TSRoleUser tr : tsRoleUserList) {
//                if (tr.getTSUser() != null && StringUtil.isNotEmpty(tr.getTSUser().getStatus()) && tr.getTSUser().getStatus().equals(Globals.User_Normal)) {
//                    if (StringUtil.isNotEmpty(tr.getTSUser().getEmail())) {
//                        ZyEmailEntity eMail = new ZyEmailEntity();
//                        eMail.setEmailSubject(emailTitle);
//                        eMail.setEmailReceiver(tr.getTSUser().getEmail());
//                        SendMailUtil.sendFtlMail(eMail, "mail_wx_sub_service.ftl", paraMap1, systemService);
//                        System.out.println("给HD发送邮件。。。。");
//                    }
//
//                }
//            }
//        }
     // end 181221 Amy 修改收件人为组邮箱 
    }

    /**
     * 调用添加积分
     *
     * @param openid
     * @param type
     */
    @Override
    public void AccRepard(String openid, String type) {
        String jsonString = "";
        Map map = new HashMap();
        map.put("openid", openid);
        map.put("type", type);
        String json = JSON.toJSONString(map);
        String getOrderNewsUrl = StaticValue.WX_PAGE_SHOULI;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(getOrderNewsUrl);
        try {
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            StringEntity entity = new StringEntity(json.toString(), "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            response = httpclient.execute(httpPost);

            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                jsonString = EntityUtils.toString(responseEntity);
                System.out.println("请求返回:" + state + "(" + jsonString + ")");
            } else {
                System.out.println("请求返回:" + state + "(" + jsonString + ")");
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //系统日志
        systemService.addLog("微信用户：" + openid + " 添加积分。", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
    }


    public String sendMsgForWx(List<Map<String, String>> list) {
        System.out.println("发送微信消息");
        String jsonString = "";
        try {
            JSONArray tpl = new JSONArray();
            if (list.size() > 0) {
                for (Map<String, String> map : list) {
                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("openid", map.get("openid"));
                    jsonParam.put("message", map.get("message"));
                    tpl.add(jsonParam);
                    //系统日志
                    systemService.addLog("发送微信消息。用户：" + map.get("openid") + "。内容：" + map.get("message"), Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

                }
            }
            JSONObject jsonArr = new JSONObject();
            jsonArr.put("tpl", tpl);

            System.out.println("tplPost:" + jsonArr.toString());
            String url = StaticValue.WX_SEND_MSG_NEW;
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            HttpPost httpPost = new HttpPost(url);
            try {
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-Type", "application/json");
                StringEntity entity = new StringEntity(jsonArr.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                response = httpclient.execute(httpPost);
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == org.apache.http.HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    jsonString = EntityUtils.toString(responseEntity);
                    System.out.println("返回：" + jsonString);
                } else {
                    System.out.println("请求返回:" + state + "(" + url + ")");
                }

            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("微信发送异常");
        }
        return jsonString;
    }


    public String noticeAddLevel(String openId, String type) {
        String jsonString = "";
        String url = StaticValue.WX_PAGE_SHOULI;
        try {
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("openid", openId);
            jsonParam.put("type", type);
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            HttpPost httpPost = new HttpPost(url);
            try {
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-Type", "application/json");
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);

                response = httpclient.execute(httpPost);


                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == org.apache.http.HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    jsonString = EntityUtils.toString(responseEntity);
                    System.out.println("jsonString:" + jsonString);
                } else {
                    System.out.println("请求返回:" + state + "(" + url + ")");
                }

            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //系统日志
            if ("PROMOTE_DIAMOND".equals(type)) {
                systemService.addLog("升级微信用户 " + openId + " 为钻石", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
            } else {
                systemService.addLog("升级微信用户 " + openId + " 为金牌", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("微信发送异常");
        }
        return jsonString;
    }


    public void addServiceLog(String serviceId) throws Exception {
        CbsServiceEntity service = null;
        System.out.println("添加日志");
        if (StringUtil.isNotEmpty(serviceId)) {
            service = systemService.get(CbsServiceEntity.class, serviceId);
        }
        CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
        cbsServiceLog.setDescription("创建服务单");
        cbsServiceLog.setCbsServiceId(service);
        cbsServiceLog.setCreateName(service.getCreateName());
        cbsServiceLog.setCreateBy(service.getCreateBy());
        cbsServiceLog.setCreateDate(new Date());
        cbsServiceLog.setLogType(StaticValue.Close_Service_Log_Type_2);
        systemService.save(cbsServiceLog);
        //系统日志
        systemService.addLog("微信用户创建服务单" + service.getCode() + "。", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

    }

    @Override
    public void bestEvaluate(String serviceId) {
        System.out.println("自动添加好评");
        CbsServiceEntity service = null;
        CbsInspectionEvaluateEntity evaluate = null;
        List<CbsInspectionEvaluateEntity> evaluateEntity = systemService.findHql("from CbsInspectionEvaluateEntity where busType='type_2' and cbsService.id='" + serviceId + "'");
        if (evaluateEntity != null && evaluateEntity.size() > 0) {
            evaluate = evaluateEntity.get(0);
        } else {
            evaluate = new CbsInspectionEvaluateEntity();
        }
        if (StringUtil.isNotEmpty(serviceId)) {
            service = systemService.get(CbsServiceEntity.class, serviceId);
            evaluate.setCbsService(service);
        }
        evaluate.setBusType("type_2");
        evaluate.setLastEvaluate(5);
        evaluate.setServiceEvaluate(5);
        evaluate.setTalkEvaluate(5);
        evaluate.setEffectEvaluate(5);
        evaluate.setTrainEvaluate(5);
        evaluate.setSkillEvaluate(5);
        evaluate.setOpinion("");
        evaluate.setEvaluateTime(new Date());
        evaluate.setEvaluateName("");
        evaluate.setEvaluateState(StaticValue.DIC_EVALUATE_STATE_1);
        systemService.saveOrUpdate(evaluate);
        //系统日志
        systemService.addLog("服务单：" + service.getCode() + "自动添加好评。", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

    }

    @Override
    public void autoBestEvaluate() {
        System.out.println("0点自动好评");
        CbsServiceEntity service = null;
        //8天自动好评
        long time = 8 * 24 * 60 * 60 * 1000;
        Date nowDate = new Date();
        long nowTime = nowDate.getTime();
        List<CbsInspectionEvaluateEntity> evaluateEntityList = systemService.findHql("from CbsInspectionEvaluateEntity where busType='type_2' and evaluateState='" + StaticValue.DIC_EVALUATE_STATE_0 + "'");
        if (evaluateEntityList != null && evaluateEntityList.size() > 0) {
            for (CbsInspectionEvaluateEntity evaluate : evaluateEntityList) {
                if (StringUtil.isNotEmpty(evaluate.getCreateDate())) {
                    long createTime = evaluate.getCreateDate().getTime();
                    if ((nowTime - createTime) > time) {
                        evaluate.setBusType("type_2");
                        evaluate.setLastEvaluate(5);
                        evaluate.setServiceEvaluate(5);
                        evaluate.setTalkEvaluate(5);
                        evaluate.setEffectEvaluate(5);
                        evaluate.setTrainEvaluate(5);
                        evaluate.setSkillEvaluate(5);
                        evaluate.setOpinion("");
                        evaluate.setEvaluateTime(new Date());
                        evaluate.setEvaluateName("");
                        evaluate.setEvaluateState(StaticValue.DIC_EVALUATE_STATE_1);
                        systemService.saveOrUpdate(evaluate);
                        //系统日志
                        if (evaluate.getCbsService() != null) {
                            service = evaluate.getCbsService();
                            systemService.addLog("服务单：" + service.getCode() + "自动添加好评。", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
                        }
                    }
                }
            }
        }


    }
}
